package ext.opensource.netty.common;

import java.text.SimpleDateFormat;

public class NettyLog {
	private static class LogInfo {
		public String name;
		public String methodName;
		public long lineNumber;
		public String threadName;

		@Override
		public String toString() {
			//return " [" + threadName + "] " + name + " - " + methodName + "- " + lineNumber + "";
			return name;
		}
	}

	private static String getCurDateTimeStr() {
		final SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		return dateformat.format(System.currentTimeMillis());
	}

	private static LogInfo getEnterClassName() {
		final Thread cur = Thread.currentThread();
		final LogInfo logInfo = new LogInfo();
		final int iLevel = 4;
		if (cur != null) {
			final StackTraceElement[] ary = cur.getStackTrace();
			logInfo.threadName = cur.getName();
			if ((ary != null) && (ary.length > iLevel)) {
				logInfo.name = ary[iLevel].getClassName();
				logInfo.methodName = ary[iLevel].getMethodName();
				logInfo.lineNumber = ary[iLevel].getLineNumber();
			}
		}
		return logInfo;
	}

	private static void baseinfo(final String msg) {
		System.err.println(
				String.format("%s info - %s : %s", NettyLog.getCurDateTimeStr(), NettyLog.getEnterClassName(), msg));
	}

	private static void basedebug(final String msg) {
		System.err.println(
				String.format("%s [DEBUG] - %s : %s", NettyLog.getCurDateTimeStr(), NettyLog.getEnterClassName(), msg));
	}

	private static void baseerror(final String msg) {
		System.err.println(
				String.format("%s [ERROR] - %s : %s", NettyLog.getCurDateTimeStr(), NettyLog.getEnterClassName(), msg));
	}

	public static void info(final String msg) {
		NettyLog.baseinfo(msg);
	}

	public static void info(final String msg, final Object... arguments) {
		final String newMsg = msg.replaceAll("\\{\\}", "\\%s");
		NettyLog.baseinfo(String.format(newMsg, arguments));
	}

	public static void error(final String msg) {
		NettyLog.baseerror(msg);

	}

	public static void error(final String msg, final Object... arguments) {
		final String newMsg = msg.replaceAll("\\{\\}", "\\%s");
		NettyLog.baseerror(String.format(newMsg, arguments));
	}

	public static void error(final String msg, final Exception exp) {
		NettyLog.baseerror(msg);
		if (null != exp) {
			exp.printStackTrace();
		}
	}

	public static void debug(final String msg) {
		NettyLog.basedebug(msg);
	}

	public static void debug(final String msg, final Object... arguments) {
		final String newMsg = msg.replaceAll("\\{\\}", "\\%s");
		NettyLog.basedebug(String.format(newMsg, arguments));
	}
}
